// 获取tbody
let tbody=document.querySelector('tbody')
let arr;
let tim
axios.post('/mock').then((res) => {
    console.log(res.data);
    fn(res.data)
    arr=res.data
})
// 渲染数据
function fn(arr){
    tbody.innerHTML=arr.map(item=>{
       return `
            <tr>
                <td><input type="checkbox"></td>
                <td><img src=${item.img}${item.name}></td>
                <td>${item.pice}</td>
                <td>
                    <span>-</span>
                    <span>${item.count}</span>
                    <span>+</span>
                </td>
                <td>${item.count*item.pice}</td>
                <td>
                    <span>删除</span>
                    <span>移入关注</span>
                </td>
            </tr>
        `
    }).join('')
}
// 给tbody添加点击事件
tbody.onclick = function(e) {
    el=e.target;
    // 判断点击的是不是 +
    if(el.innerHTML==='+'){
        el.previousElementSibling.innerHTML++;
        // 获取下标
        let index=[...tbody.children].indexOf(el.parentNode.parentNode)
        arr[index].count=el.previousElementSibling.innerHTML;
        el.parentNode.nextElementSibling.innerHTML=el.previousElementSibling.innerHTML*el.parentNode.previousElementSibling.innerHTML;
        clearTimeout(tim)
        tim=setTimeout(()=>{
            axios.post('/updata',arr);
        },300)
    }
    // 判断点击的是不是 -
    if(el.innerHTML==='-'){
        el.nextElementSibling.innerHTML--;
        if(el.nextElementSibling.innerHTML<=1){
            el.nextElementSibling.innerHTML=1
        }
        // 获取下标
        let index=[...tbody.children].indexOf(el.parentNode.parentNode);
        arr[index].count=el.nextElementSibling.innerHTML;
        el.parentNode.nextElementSibling.innerHTML=el.nextElementSibling.innerHTML*el.parentNode.previousElementSibling.innerHTML;
        clearTimeout(tim);
        tim=setTimeout(()=>{
            axios.post('/updata',arr);
        },300)
    }
    // 判断点击的是不是删除
    if(el.innerHTML==='删除'){
        // 获取下标
        let index=[...tbody.children].indexOf(el.parentNode.parentNode);
        arr.splice(index, 1)
        axios.post('/updata',arr);
        el.parentNode.parentNode.remove()
    }
    // 判断点击的是不是移入关注
    if(el.innerHTML==='移入关注'){
        // 获取下标
        let index=[...tbody.children].indexOf(el.parentNode.parentNode);
        axios.post(`/up/index/${index}`,arr)
        el.parentNode.parentNode.remove()
    }
}